package com.ys168.gam.shortestpath.util;

import java.awt.geom.Point2D;

/**
 *
 * @author Jason Krebs
 * @date 2015年2月6日
 */
public class MoveHelper {

    private static final int STEP = 8;

    /**
     *
     * @param source
     * @param target
     * @return
     */
    public static Point2D getNextLocation(Point2D current, Point2D source, Point2D target) {
        if (current.equals(target)) {
            return source;
        }

        if (Math.abs(current.getX() - target.getX()) <= STEP && Math.abs(current.getY() - target.getY()) <= STEP) {
            return target;
        }

        double x1 = source.getX();
        double y1 = source.getY();
        double x2 = target.getX();
        double y2 = target.getY();
        int directionX = x1 < x2 ? 1 : -1;
        int directionY = y1 < y2 ? 1 : -1;

        if (x1 == x2) {// 垂直线,k=∞
            return new Point2D.Double(target.getX(), current.getY() + STEP * directionY);
        }

        double k = (y2 - y1) / (x2 - x1);
        double stepX = STEP / (Math.sqrt(k * k + 1));
        double stepY = Math.abs(k) * stepX;

        return new Point2D.Double(current.getX() + stepX * directionX, current.getY() + stepY * directionY);
    }

    public static void main(String[] args) {
        Point2D a = new Point2D.Double(1, 1);
        Point2D b = new Point2D.Double(10, 21);
        Point2D n = getNextLocation(a, a, b);
        System.out.println(n);
    }
}
